package com.dy.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dy.security.entity.PersistentToken;
import com.dy.security.mapper.PersistentTokenMapper;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: ding-yu
 * @Date: 2022/5/20 14:27
 * @Desctiption: (描述)
 */
@Service
public class MypersistentTokenRepositoryImpl implements PersistentTokenRepository {

    @Resource
    private PersistentTokenMapper baseMapper;

    @Override
    public void createNewToken(PersistentRememberMeToken token) {
        PersistentToken persistentToken = new PersistentToken();
        persistentToken.setTokenValue(token.getTokenValue())
                        .setSeries(token.getSeries())
                        .setUserName(token.getUsername())
                        .setUserLast(token.getDate());
        baseMapper.insert(persistentToken);
    }

    @Override
    public void updateToken(String series, String tokenValue, Date lastUsed) {
        PersistentToken persistentToken = baseMapper.selectOne(new LambdaQueryWrapper<PersistentToken>().eq(PersistentToken::getSeries, series));
        persistentToken.setTokenValue(tokenValue)
                        .setUserLast(lastUsed);
        baseMapper.updateById(persistentToken);
    }

    @Override
    public PersistentRememberMeToken getTokenForSeries(String seriesId) {
        PersistentToken persistentToken = baseMapper.selectById(seriesId);
        return new PersistentRememberMeToken(persistentToken.getUserName()
                ,persistentToken.getSeries()
                ,persistentToken.getTokenValue()
                ,persistentToken.getUserLast());
    }

    @Override
    public void removeUserTokens(String username) {
        baseMapper.delete(new LambdaQueryWrapper<PersistentToken>().eq(PersistentToken::getUserName, username));
    }
}

